package lines.gameengine.tracer;

import lines.gameengine.FieldPoint;
import lines.gameengine.ICell;
import lines.gameengine.IField;

import java.util.ArrayList;
import java.util.List;

import static lines.gameengine.util.LinesEngineConstants.*;

/**
 * @author vpotapenko
 */
public class FieldTracer implements IFieldTracer {

    private int tracerField[][];

    private FieldPoint endPoint;

    private FieldPeerLocator locator;

    @Override
    public void update(IField field) {
        checkInitializedField(field.getWidth(), field.getHeight());
        for (int x = 0; x < field.getWidth(); x++) {
            for (int y = 0; y < field.getHeight(); y++) {
                ICell cell = field.getCell(x, y);
                updatePoint(cell);
            }
        }
    }

    private void updatePoint(ICell cell) {
        FieldPoint point = cell.getPoint();
        tracerField[point.getX()][point.getY()] = !cell.isEmpty() ? BUSY_CELL : 0;
    }

    private void checkInitializedField(int width, int height) {
        if (tracerField != null) return;

        tracerField = new int[width][height];
        locator = new FieldPeerLocator(width, height);
    }

    @Override
    public SearchResult findTrace(FieldPoint start, FieldPoint end) {
        checkOnValidPoints(start, end);

        endPoint = end;

        setValue(start, START_CELL);
        setValue(end, END_CELL);

        doWaveIterations();
        if (!hasTrace()) return TRACE_NOT_FOUND_RESULT;

        List<FieldPoint> trace = fillTrace();
        return new SearchResult(trace);
    }

    private void doWaveIterations() {
        boolean doIteration = true;
        while (doIteration) {
            int count = 0;
            for (int x = 0; x < getWidth(); x++) {
                for (int y = 0; y < getHeight(); y++) {
                    count += fillPeerValues(x, y);
                }
            }
            doIteration = (count > 0) && !hasTrace();
        }
    }

    private int fillPeerValues(int x, int y) {
        final int value = getValue(x, y);
        if (value <= 0 && value != START_CELL) return 0;

        int nextValue = value == START_CELL ? 1 : value + 1;
        int count = 0;

        locator.init(new FieldPoint(x, y));
        while (locator.hasNext()) {
            FieldPoint peer = locator.next();
            if (getValue(peer) != 0) continue;

            setValue(peer, nextValue);
            count++;
        }
        return count;
    }

    private int getHeight() {
        return getWidth() > 0 ? tracerField[0].length : 0;
    }

    private int getWidth() {
        return tracerField.length;
    }

    private boolean hasTrace() {
        locator.init(endPoint);
        while (locator.hasNext()) {
            int value = getValue(locator.next());
            if (value > 0 || value == START_CELL) return true;
        }
        return false;
    }

    private int getValue(FieldPoint point) {
        return getValue(point.getX(), point.getY());
    }

    private int getValue(int x, int y) {
        return tracerField[x][y];
    }

    private void setValue(FieldPoint point, int value) {
        tracerField[point.getX()][point.getY()] = value;
    }

    private List<FieldPoint> fillTrace() {
        List<FieldPoint> trace = new ArrayList<FieldPoint>();
        trace.add(0, endPoint);

        findNextStepTrace(trace, endPoint);
        return trace;
    }

    private void findNextStepTrace(List<FieldPoint> trace, FieldPoint point) {
        FieldPoint minimumPoint = findMinimumValuePoint(point);

        trace.add(0, minimumPoint);
        if (getValue(minimumPoint) != START_CELL) findNextStepTrace(trace, minimumPoint);
    }

    private FieldPoint findMinimumValuePoint(FieldPoint point) {
        locator.init(point);
        FieldPoint minimumPoint = null;
        while (locator.hasNext()) {
            FieldPoint peer = locator.next();
            if (getValue(peer) == START_CELL) return peer;

            if (getValue(peer) == 0 || getValue(peer) < 0) continue;

            if (minimumPoint == null || getValue(minimumPoint) > getValue(peer)) {
                minimumPoint = peer;
            }
        }
        return minimumPoint;
    }

    private void checkOnValidPoints(FieldPoint start, FieldPoint end) {
        if (start == null) throw new IllegalArgumentException("Start point must be not null");

        if (end == null) throw new IllegalArgumentException("End point must be not null");
    }
}
